package com.littlerpc.protocol.codec.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.littlerpc.protocol.codec.Serializer;
import com.littlerpc.protocol.exception.SerializerException;

import java.io.IOException;

/**
 *
 * @author ChengPeng
 * @date 2017/6/13
 */
public class JacksonSerializer implements Serializer {

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    @Override
    public <T> byte[] serialize(T obj) {
        try {
            return OBJECT_MAPPER.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {

        try {
            return OBJECT_MAPPER.readValue(bytes,clazz);
        } catch (IOException e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }
}
